package com.novel.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.novel.mapper.*;
import com.novel.common.exception.CustomerException;
import com.novel.pojo.novel.*;
import com.novel.pojo.system.ChapterOrder;
import com.novel.pojo.system.DownLoadInfo;
import com.novel.pojo.system.User;
import com.novel.utils.RedisUtils;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Transactional
public class NovelService {

    @Autowired
    private NovelMapper novelMapper;

    @Autowired
    private NovelCategoryMapper categoryMapper;

    @Autowired
    private ChapterOrderMapper chapterOrderMapper;

    @Autowired
    private DownLoadInfoMapper downLoadInfoMapper;

    @Autowired
    private NovelRewardMapper novelRewardMapper;

    @Autowired
    private NovelRecommendMapper novelRecommendMapper;

    @Autowired
    private NovelCommentMapper novelCommentMapper;

    @Autowired
    private NovelChapterMapper novelChapterMapper;

    @Autowired
    private NovelShelfMapper novelShelfMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据小说id获取小说信息
     */
    public Novel getNovelInfoByNovelId(String novelId) {
        return novelMapper.selectByPrimaryKey(novelId);
    }


    /**
     * 小说删除
     * 1.小说信息删除
     * 2.小说章节全部删除
     * 3.删除小说和类型之间的关系
     * 4.打赏信息 小说部分置空
     * 5.评论部分，小说信息制空
     * 6.推荐部分，小说信息制空
     * 7.VIP章节部分，小说信息制空，购买记录保留
     * 8.小说下载部分，小说信息制空
     * 9.删除书架内容
     */
    @Transactional
    public boolean deleteNovel(String novelId) {
        int count;
        //查询章节信息
        Example example = new Example(NovelChapter.class);
        example.createCriteria().andEqualTo("novelId", novelId);
        List<NovelChapter> chapterList = novelChapterMapper.selectByExample(example);

        if (CollectionUtils.isNotEmpty(chapterList)) {
            List<String> vipChapterIds = chapterList.stream().filter(v -> v.getVip() == 1)
                    .map(NovelChapter::getChapterId)
                    .collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(vipChapterIds)) {
                //删除VIP章节
                Example chapterOrderExample = new Example(ChapterOrder.class);
                chapterOrderExample.createCriteria().andIn("chapterId", vipChapterIds);
                count = chapterOrderMapper.deleteByExample(chapterOrderExample);

                if (count != vipChapterIds.size()) {
                    throw new CustomerException("删除失败!");
                }
            }
            //删除章节信息
            Example chapterExample = new Example(NovelChapter.class);
            chapterExample.createCriteria().andEqualTo("novelId", novelId);
            count = novelChapterMapper.deleteByExample(chapterExample);

            if (count != chapterList.size()) {
                throw new CustomerException("删除失败!");
            }

        }

        //小说下载部分，删除
        Example downExample = new Example(DownLoadInfo.class);
        downExample.createCriteria().andEqualTo("novelId", novelId);
        downLoadInfoMapper.deleteByExample(downExample);

        //打赏部分，删除
        Example rewardExample = new Example(NovelReward.class);
        rewardExample.createCriteria().andEqualTo("novelId", novelId);
        novelRewardMapper.deleteByExample(rewardExample);


        //推荐部分，删除
        Example recommendExample = new Example(NovelRecommend.class);
        recommendExample.createCriteria().andEqualTo("novelId", novelId);
        novelRecommendMapper.deleteByExample(recommendExample);


        //评论，删除
        Example commentExample = new Example(NovelComment.class);
        commentExample.createCriteria().andEqualTo("novelId", novelId);
        novelCommentMapper.deleteByExample(commentExample);


        //书架，删除
        Example selfExample = new Example(NovelShelf.class);
        selfExample.createCriteria().andEqualTo("novelId", novelId);
        novelShelfMapper.deleteByExample(selfExample);

        //删除小说类型部分
        count = categoryMapper.deleteNovelCategoryByNovelId(novelId);
        if (count != 1) {
            throw new CustomerException("删除失败!");
        }

        //删除小说信息
        count = novelMapper.deleteByPrimaryKey(novelId);
        if (count != 1) {
            throw new CustomerException("删除失败!");
        }

        //清空redis缓存
        redisUtils.deleteByKey(novelId);

        return true;
    }

    /**
     * 小说关闭
     */
    @Transactional
    public boolean closeNovelByAuthor(String novelId, String authorId) {

        Novel novel = novelMapper.selectByPrimaryKey(novelId);

        if (StringUtils.equals(authorId, novel.getAuthorId())) {

            if (novel.getEnd() == 1) {
                throw new CustomerException("本书状态已经是完结状态");
            }

            novel.setEnd(1);
            return novelMapper.updateByPrimaryKey(novel) == 1;
        }
        throw new CustomerException("你不是这本书作者,无法修改本书状态");
    }

    /**
     * 修改小说点击量
     */
    @Transactional
    public boolean updateNovelClickCount(String novelId, Long novelClick) {
        Novel record = new Novel();
        record.setNovelId(novelId);
        record.setNovelClick(novelClick);
        return novelMapper.updateByPrimaryKeySelective(record) == 1;
    }


    /**
     * 统计某个作家作品总数
     */
    public int countNovelByAuthorId(String authorId) {
        Novel record = new Novel();
        record.setAuthorId(authorId);
        return novelMapper.selectCount(record);
    }

    /**
     * 添加新书
     * 1.小说信息来自于用户填写
     * 2.书籍类型id，来自于页面选择框选择好的
     *
     * @param novel 书籍信息
     */
    public boolean addNovel(Novel novel) {
        //查询类型信息
        NovelCategory category = categoryMapper.selectByPrimaryKey(novel.getCategory());

        if (Objects.isNull(category)) {
            throw new CustomerException("请选择有效的书籍类型");
        }

        novel.setCategory(category.getCName());

        //添加书籍
        int row = novelMapper.insertSelective(novel);
        if (row != 1) {
            throw new CustomerException("添加书籍失败");
        }
        //给书籍添加类型
        row = categoryMapper.setNovelCategory(novel.getNovelId(), category.getCId());
        if (row != 1) {
            throw new CustomerException("书籍分类失败");
        }
        return true;
    }

    /**
     * 分页查询小说信息
     * 根据当前页号以及小说的类型
     *
     * @param pageNum  当前页号
     * @param pageSize 页大小
     * @param category 小说类型
     */
    public PageInfo<Novel> findAllNovelByPage(int pageNum, int pageSize, String category) {
        //设置分页信息
        PageHelper.startPage(pageNum, pageSize);
        //创建小说查询条件对象
        Example example = new Example(Novel.class);
        //判断有没有传入类型限定
        if (StringUtils.isNotBlank(category)) {
            //如果传入了类型的限定，那么就要过滤掉那些不是的小说
            example.createCriteria().andEqualTo("category", category);
        }
        //设置查询结果排序
        example.setOrderByClause("last_time desc");
        //查询小说数据
        List<Novel> novelList = novelMapper.selectByExample(example);
        //返回分页后的数据
        return new PageInfo<>(novelList);
    }

    /**
     * 根据书名模糊查询书籍基本信息
     *
     * @param novelName 书名
     */
    public List<Novel> findNovelByName(String novelName) {
        //创建查询条件对象
        Example example = new Example(Novel.class);
        //封装查询条件
        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("novelName", "%" + novelName + "%");
        //返回查询到的数据
        return novelMapper.selectByExample(example);
    }

    /**
     * 根据书籍id查询书籍基本信息
     *
     * @param id 书籍id
     */
    public Novel findNovelById(String id) {
        return novelMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据用户输入的作者名字模糊查询
     *
     * @param authorName 作者名字
     */
    public List<Novel> findNovelByAuthor(String authorName) {
        //创建条件查询对象
        Example example = new Example(Novel.class);
        //封装查询条件
        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("authorName", "%" + authorName + "%");
        //根据查询条件查询数据
        return novelMapper.selectByExample(example);
    }

    /**
     * 根据作者id查询作者小说列表信息
     */
    public PageInfo<Novel> findNovelByAuthorId(String authorId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Example example = new Example(Novel.class);
        example.createCriteria().andEqualTo("authorId", authorId);
        return new PageInfo<>(novelMapper.selectByExample(example));
    }

    /**
     * 根据作者id查询作者小说列表信息
     */
    public List<Novel> findNovelByAuthorId(String authorId) {
        Example example = new Example(Novel.class);
        example.selectProperties("novelId", "novelName");
        example.createCriteria().andEqualTo("authorId", authorId);
        return novelMapper.selectByExample(example);
    }


}
